from django.db import models
from django.contrib.auth.models import User


class Company(models.Model):
    # Each company under analysis
    symbol = models.CharField('Stock Symbol', max_length=10)
    name = models.CharField('Company Name', max_length=100)
    lastSale = models.CharField('Last Sale', max_length=20, null=True, blank=True)
    marketCap = models.CharField('Market Cap', max_length=20, null=True, blank=True)
    adrTso =  models.CharField('Adr Tso', max_length=20, null=True, blank=True)
    ipoYear = models.CharField('IPO Year', max_length=4, null=True, blank=True)
    sector = models.CharField('Sector', max_length=100, null=True, blank=True)
    industry = models.CharField('Industry', max_length=200, null=True, blank=True)
    summaryQuote = models.CharField('Summary Quote', max_length=200, null=True, blank=True)
    exchange = models.CharField('Stock Exchange', max_length=10, null=True, blank=True)
    date_extracted = models.DateTimeField('Date extracted', null=True, blank=True)
    class Meta:
        verbose_name = "Company"
        verbose_name_plural = "Companies"
        ordering = ["name"]

    def __str__(self):
        return self.name+'('+self.symbol+')'

class CompanyFinancials(models.Model):
    company=models.ForeignKey(Company)
    quarter=models.CharField('Quarter', max_length=1)
    year = models.CharField('Year', max_length=4)
    total_assets = models.CharField('Total Assets', max_length=20, null=True, blank=True)
    total_liability = models.CharField('Total Liability', max_length=20, null=True, blank=True)
    current_assets = models.CharField('Current Assets', max_length=20, null=True, blank=True)
    current_liability = models.CharField('Current Liability', max_length=20, null=True, blank=True)
    retained_earnings = models.CharField('Retained Earnings', max_length=20, null=True, blank=True)
    market_capital = models.CharField('Market Capital', max_length=20, null=True, blank=True)
    ebitda = models.CharField('EBITDA', max_length=20, null=True, blank=True)
    sales = models.CharField('Sales', max_length=20, null=True, blank=True)
    stockprice = models.CharField('Last Stock Price', max_length=20, null=True, blank=True)
    date_extracted = models.DateTimeField('Date extracted', null=True, blank=True)

    class Meta:
        verbose_name = "Company Financial"
        verbose_name_plural = "Company Financials"

    def __str__(self):
        return self.company.name+" "+self.quarter+" - "+self.year


class CompanyKeyStats(models.Model):
    company=models.ForeignKey(Company)
    marketcap = models.CharField('Market Cap', max_length=40, null=True, blank=True)
    marketcap_term = models.CharField('Market Cap Term', max_length=40, null=True, blank=True)
    enterprisevalue = models.CharField('Enterprise Value', max_length=40, null=True, blank=True)
    enterprisevalue_term = models.CharField('Enterprise Value Term', max_length=40, null=True, blank=True)
    trailingpe = models.CharField('Trailing PE', max_length=40, null=True, blank=True)
    trailingpe_term = models.CharField('Trailing Pe Term', max_length=40, null=True, blank=True)
    forwardpe = models.CharField('Forward PE', max_length=40, null=True, blank=True)
    forwardpe_term = models.CharField('Forward PE Term', max_length=40, null=True, blank=True)
    pegratio = models.CharField('PEG Ratio', max_length=40, null=True, blank=True)
    pegratio_term = models.CharField('PEG Ratio Term', max_length=40, null=True, blank=True)
    pricesales = models.CharField('Price Sales', max_length=40, null=True, blank=True)
    pricesales_term = models.CharField('Price Sales Term', max_length=40, null=True, blank=True)
    pricebook = models.CharField('Price Book', max_length=40, null=True, blank=True)
    pricebook_term = models.CharField('Price Book Term', max_length=40, null=True, blank=True)
    enterprisevaluerevenue = models.CharField('Enterprise Value Revenue', max_length=40, null=True, blank=True)
    enterprisevaluerevenue_term = models.CharField('Enterprise Value Term', max_length=40, null=True, blank=True)
    enterprisevalueebitda = models.CharField('Enterprise Value Ebitda', max_length=40, null=True, blank=True)
    enterprisevalueebitda_term = models.CharField('Enterprise Value Ebitda Term', max_length=40, null=True, blank=True)
    fiscalyearends= models.CharField('Fiscal Year Ends', max_length=40, null=True, blank=True)
    mostrecentquarter= models.CharField('Most Recent Quarter', max_length=40, null=True, blank=True)
    profitmargin= models.CharField('Profit Margin', max_length=40, null=True, blank=True)
    profitmargin_term= models.CharField('Profit Margin Term', max_length=40, null=True, blank=True)
    operatingmargin= models.CharField('Operating Margin', max_length=40, null=True, blank=True)
    operatingmargin_term= models.CharField('Operating Margin Term', max_length=40, null=True, blank=True)
    returnonassets= models.CharField('Return On Assets', max_length=40, null=True, blank=True)
    returnonassets_term= models.CharField('Return on Assets Term', max_length=40, null=True, blank=True)
    returnonequity= models.CharField('Return On Equity', max_length=40, null=True, blank=True)
    returnonequity_term= models.CharField('Return on Equity Term', max_length=40, null=True, blank=True)
    revenue = models.CharField('Revenue', max_length=40, null=True, blank=True)
    revenue_term = models.CharField('Revenue Term', max_length=40, null=True, blank=True)
    revenuepershare = models.CharField('Revenue Per Share', max_length=40, null=True, blank=True)
    revenuepershare_term = models.CharField('Revenue Per Share Term', max_length=40, null=True, blank=True)
    quarterlyrevenuegrowth = models.CharField('Quarterly Revenue Growth', max_length=40, null=True, blank=True)
    quarterlyrevenuegrowth_term = models.CharField('Quarterly Revenue Growth Term', max_length=40, null=True, blank=True)
    grossprofit = models.CharField('Gross Profit', max_length=40, null=True, blank=True)
    grossprofit_term = models.CharField('Gross Profit Term', max_length=40, null=True, blank=True)
    ebitda = models.CharField('Ebitda', max_length=40, null=True, blank=True)
    ebitda_term = models.CharField('Ebitda Term', max_length=40, null=True, blank=True)
    netincomeavltocommon = models.CharField('Net Income Available to Common', max_length=40, null=True, blank=True)
    netincomeavltocommon_term = models.CharField('Net Income Available to Common Term', max_length=40, null=True, blank=True)
    dilutedeps = models.CharField('Diluted EPS', max_length=40, null=True, blank=True)
    dilutedeps_term = models.CharField('Diluted EPS Term', max_length=40, null=True, blank=True)
    quarterlyearningsgrowth = models.CharField('Quarterly Earnings Growth', max_length=40, null=True, blank=True)
    quarterlyearningsgrowth_term = models.CharField('Quarterly Earnings Growth Term', max_length=40, null=True, blank=True)
    totalcash = models.CharField('Total Cash', max_length=40, null=True, blank=True)
    totalcash_term = models.CharField('Total Cash Term', max_length=40, null=True, blank=True)
    totalcashpershare = models.CharField('Total Cash per Share', max_length=40, null=True, blank=True)
    totalcashpershare_term = models.CharField('Total Cash per Share Term', max_length=40, null=True, blank=True)
    totaldebt = models.CharField('Total Debt', max_length=40, null=True, blank=True)
    totaldebt_term = models.CharField('Total Debt Term', max_length=40, null=True, blank=True)
    totaldebtequity = models.CharField('Total Debt Equity', max_length=40, null=True, blank=True)
    totaldebtequity_term = models.CharField('Total Debt Equity Term', max_length=40, null=True, blank=True)
    currentratio = models.CharField('Current Ratio', max_length=40, null=True, blank=True)
    currentratio_term = models.CharField('Current Ratio Term', max_length=40, null=True, blank=True)
    bookvaluepershare = models.CharField('Book Value Per Share', max_length=40, null=True, blank=True)
    bookvaluepershare_term = models.CharField('Book Value Per Share Term', max_length=40, null=True, blank=True)
    operatingcashflow = models.CharField('Operating Cash Flow', max_length=40, null=True, blank=True)
    operatingcashflow_term = models.CharField('Operating Cash Flow Term', max_length=40, null=True, blank=True)
    leveredfreecashflow = models.CharField('Levered Free Cash Flow', max_length=40, null=True, blank=True)
    leveredfreecashflow_term = models.CharField('Levered Free Cash Flow Term', max_length=40, null=True, blank=True)
    beta = models.CharField('Beta', max_length=40, null=True, blank=True)
    p52weekchange = models.CharField('p52weekchange', max_length=40, null=True, blank=True)
    sp500p52weekchange = models.CharField('sp500p52weekchange', max_length=40, null=True, blank=True)
    p52weekhigh = models.CharField('p52weekhigh', max_length=40, null=True, blank=True)
    p52weekhigh_term = models.CharField('p52weekhigh Term', max_length=40, null=True, blank=True)
    p52weeklow = models.CharField('p52weeklow', max_length=40, null=True, blank=True)
    p52weeklow_term = models.CharField('p52weeklow Term', max_length=40, null=True, blank=True)
    p50daymovingaverage = models.CharField('p50daymovingaverage', max_length=40, null=True, blank=True)
    p200daymovingaverage = models.CharField('p200daymovingaverage', max_length=200, null=True, blank=True)
    averagevolume = models.CharField('Average Volume', max_length=400, null=True, blank=True)
    averagevolume_term = models.CharField('Average Volume Term', max_length=40, null=True, blank=True)
    sharesoutstanding= models.CharField('Shares Outstanding', max_length=40, null=True, blank=True)
    sfloat=models.CharField('Float', max_length=40, null=True, blank=True)
    percenthldbyinsiders=models.CharField('Percent Held by Insiders', max_length=40, null=True, blank=True)
    percenthldbyinstitutions=models.CharField('Percent Held by Institutions', max_length=200, null=True, blank=True)
    sharesshort=models.CharField('Shares Short', max_length=200, null=True, blank=True)
    shareshort_term=models.CharField('Shares Short Term', max_length=40, null=True, blank=True)
    shortratio=models.CharField('Short Ratio', max_length=40, null=True, blank=True)
    shortratio_term=models.CharField('Short Ratio Term', max_length=40, null=True, blank=True)
    shortpercentfloat=models.CharField('Short Percentage Float', max_length=40, null=True, blank=True)
    shortpercentfloat_term=models.CharField('Short Percentage Float Term', max_length=40, null=True, blank=True)
    forwardannualdividentrate= models.CharField('forwardannualdividentrate', max_length=40, null=True, blank=True)
    forwardannualdividentyield= models.CharField('forwardannualdividentyield', max_length=40, null=True, blank=True)
    trailingannualdividentrate= models.CharField('trailingannualdividentrate', max_length=40, null=True, blank=True)
    trailingannualdividentyield= models.CharField('trailingannualdividentyield', max_length=40, null=True, blank=True)
    p_5yearaveragedivident= models.CharField('p_5yearaveragedivident', max_length=40, null=True, blank=True)
    payoutratio= models.CharField('payoutratio', max_length=40, null=True, blank=True)
    dividentrate= models.CharField('dividentrate', max_length=40, null=True, blank=True)
    ex_dividentrate= models.CharField('ex_dividentrate', max_length=40, null=True, blank=True)
    lastsplitfactor= models.CharField('lastsplitfactor', max_length=40, null=True, blank=True)
    lastsplitfactor_term= models.CharField('lastsplitfactor_term', max_length=40, null=True, blank=True)
    lastsplitdate= models.CharField('lastsplitdate', max_length=40, null=True, blank=True)



class TwitterText(models.Model):
    # Each sentiment related to the companies under analysis and captured from the social media platforms
    twitter_user_id = models.CharField('Social User ID', max_length=255)
    twitter_user_name = models.CharField('Social User Name', max_length=100)
    twitter_text = models.CharField('Social Updates', max_length=1024)
    twitter_text_id = models.CharField('Message Id', max_length=255)
    twitter_text_timestamp = models.DateTimeField('Message Timestamp')
    twitter_text_keyword = models.CharField('Keyword', max_length=1000)
    twitter_for_training = models.IntegerField('training value', max_length=1, default=9) #9 untrained #0: trained dataset,1: dev-test dataset, 2: test dataset #4 applied dataset
    twitter_sentiment = models.IntegerField('sentiment', max_length=1, default=2)
    training_user = models.ForeignKey(User, null=True, blank=True)

    class Meta:
        verbose_name = "Twitter Text"
        verbose_name_plural = "Twitter Texts"

    def __str__(self):
        return self.twitter_text+" keyword: "+self.twitter_text_keyword

class CompanyAltmanZscore(models.Model):
    company=models.ForeignKey(Company)
    company_financials = models.ForeignKey(CompanyFinancials)
    zscore = models.CharField("Altman Z-Score", max_length=10, null=True,blank=True)
    date_updated = models.DateTimeField('Date Calculated', auto_now=True)

    class Meta:
        verbose_name = "Altman Score"
        verbose_name_plural = "Altman Scores"

    def __str__(self):
        return self.company.name+" - zscore:"+self.zscore

class CompanySentiment(models.Model):
    company = models.ForeignKey(Company)
    twitter_text = models.ForeignKey(TwitterText)
    sentiment_prob_very_negative = models.CharField('Very Negative Probability', max_length="10", null=True, blank=True)
    sentiment_prob_negative = models.CharField('Negative Probability', max_length="10", null=True, blank=True)
    sentiment_prob_neutral = models.CharField('Neutral Probability', max_length="10", null=True, blank=True)
    sentiment_prob_positive = models.CharField('Positive Probability', max_length="10", null=True, blank=True)
    sentiment_prob_very_positive = models.CharField('Very Positive Probability', max_length="10", null=True, blank=True)
    sentiment_root_value = models.CharField('Sentiment', max_length="20", null=True, blank=True)
    date_updated = models.DateTimeField('Date Calculated', auto_now=True)

    class Meta:
        verbose_name = "Company Sentiment"
        verbose_name_plural = "Company Sentiments"

    def __str__(self):
        return self.company+" - tweet: "+self.twitter_text.id+" - sentiment: "+self.sentiment_root_value

class CompanyQuoteHistory(models.Model):
    company=models.ForeignKey(Company)
    date = models.DateField('Quote Date',null=True, blank=True)
    open=models.FloatField('Open', null=True, blank=True)
    high = models.FloatField('High',null=True, blank=True)
    low = models.FloatField('Low', null=True, blank=True)
    close = models.FloatField('Close', null=True, blank=True)
    volume = models.FloatField('Volume', null=True, blank=True)
    adjs_close = models.FloatField('Adj Close', null=True, blank=True)
    symbol = models.CharField('Symbol', null=True, blank=True, max_length="10")

    class Meta:
        verbose_name = "Company Quote History"
        verbose_name_plural = "Company Quote History"

    def __str__(self):
        return self.company.name+self.date+" trend: "+(self.close - self.open)


class CompanyStocksSentimentHistory(models.Model):
    company=models.ForeignKey(Company)
    symbol = models.CharField('Stock Symbol',max_length="10", null=True, blank=True )
    date = models.DateField('Quote Date',null=True, blank=True)
    tweet_count =   models.IntegerField('Tweets', null=True, blank=True)
    sentiment = models.IntegerField('Sentiment', null=True, blank=True)
    stockopen = models.FloatField('Stock Open', null=True, blank=True)
    stockclose = models.FloatField('Stock Close', null=True, blank=True)
    stockdirection = models.IntegerField('Stock Direction', null=True, blank=True)

    class Meta:
        verbose_name = "Company Tweet Quote "
        verbose_name_plural = "Company Tweet Quotes"

    def __str__(self):
        return self.company.name+" - tweet id: "+self.twitter_text.id+" "+self.date+" trend: "+(self.close - self.open)
